package model.interfaces;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Session;

public class HibernateGenericDAO<T> implements GenericDAO<T> {
	private Class<T> persistentClass;
	private Session session;
	
	@SuppressWarnings("unchecked")
	public HibernateGenericDAO(Session session) {
		this.session = session;
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass())
				.getActualTypeArguments()[0];
	}
	@Override
	public Session getSession() {		
		return this.session;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T pesquisarPorId(Serializable id) {
		return (T) this.session.get(this.persistentClass, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> listarTodos() {
		return this.session.createCriteria(this.persistentClass).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public T salvar(T entidade) {
		return (T) this.session.merge(entidade);
	}

	@Override
	public void excluir(T entidade) {
		this.session.delete(entidade);
	}
	@Override
	public void alterar(T entidade) {
		this.session.update(entidade);
	}
}
